/*
 * ComerciosAgregarFrame.java
 *
 * Created on 16 de abril de 2008, 12:06 PM
 */
package org.contabiliad.periodofiscal;

import org.mybeans.Sesion;
import org.mybeans.ContribuyentesBeans;
import org.mybeans.ComerciosBeans;
 
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


/**
 *
 * @author  avbravo
 */
public class InicioFiscalAgregarFrame extends javax.swing.JFrame {

    Sesion sesion;
    ContribuyentesBeans contribuyentesBeans;
    ComerciosBeans comerciosBeans;

    /** Creates new form ComerciosAgregarFrame */
    public InicioFiscalAgregarFrame() {
        initComponents();
          /*
         * Fondo
         */

         
         
         

        jPanelFondo.setOpaque(false);
        setContentPane(jPanelFondo);
    /*
     * fondo
     */
        
        sesion = new Sesion();
        comerciosBeans = new ComerciosBeans();
        contribuyentesBeans = new ContribuyentesBeans();

        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        jFormattedTextFieldFechaInicio.setValue(mydate);

        CrearNuevo();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanelFondo = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldIdInicioFiscal = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButtonGuardar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jFormattedTextFieldFechaInicio = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agregar Inicio Fiscal");

        jPanelFondo.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Codigo");

        jTextFieldIdInicioFiscal.setColumns(35);
        jTextFieldIdInicioFiscal.setEditable(false);
        jTextFieldIdInicioFiscal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdInicioFiscalActionPerformed(evt);
            }
        });

        jLabel3.setText("Fecha Inicio");

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jFormattedTextFieldFechaInicio.setEditable(false);
        jFormattedTextFieldFechaInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        jFormattedTextFieldFechaInicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextFieldFechaInicioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelFondoLayout = new javax.swing.GroupLayout(jPanelFondo);
        jPanelFondo.setLayout(jPanelFondoLayout);
        jPanelFondoLayout.setHorizontalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1))
                        .addGap(37, 37, 37)
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldIdInicioFiscal, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jFormattedTextFieldFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)))
                .addContainerGap(28, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanelFondoLayout.setVerticalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldIdInicioFiscal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jFormattedTextFieldFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonRegresar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jTextFieldIdInicioFiscalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIdInicioFiscalActionPerformed
 
}//GEN-LAST:event_jTextFieldIdInicioFiscalActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed
 
    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
 

    try {
        String SIdInicioFiscal = this.jTextFieldIdInicioFiscal.getText();
        if (SIdInicioFiscal == null || SIdInicioFiscal.equals("")) {
            JOptionPane.showMessageDialog(this, "Debe introducir un numero", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdInicioFiscal.requestFocus();
            return;
        }
        int IdInicioFiscal = Integer.parseInt(SIdInicioFiscal);
        if (IdInicioFiscal <= 0) {
            JOptionPane.showMessageDialog(this, "Debe introducir un numero", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdInicioFiscal.requestFocus();
            return;
        }



        String sFecha = jFormattedTextFieldFechaInicio.getText();
        if (sFecha == null || sFecha.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione la fecha de inicio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jFormattedTextFieldFechaInicio.requestFocus();
        }



        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String sqlquery = "select * from iniciofiscal  where idmunicipio = ? and activo='si' ";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, sesion.getIdmunicipio());
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();

        if (x != 0) {
            JOptionPane.showMessageDialog(this, "Existe un registro del inicio fiscal  activo.No se puede crear otro.", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
sesion.con.close();
            return;
        }
        String sql = "INSERT into iniciofiscal  VALUES(?,?,?,?,?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setInt(1, IdInicioFiscal);

        java.util.Date myFecha = (java.util.Date) jFormattedTextFieldFechaInicio.getValue();
        java.sql.Date date = new java.sql.Date(myFecha.getTime());
        prest.setDate(2, date);
        prest.setDate(3, null);//fechaterminacion
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        prest.setDate(4, mydate);
        prest.setString(5, "si");
        prest.setString(6, sesion.getUsername());//username
        prest.setString(7, sesion.getIdmunicipio());
        int count = prest.executeUpdate();

        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Inicio de periodo fiscal guardado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception ex) {
        System.out.println("Error" + ex);
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

}//GEN-LAST:event_jButtonGuardarActionPerformed

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed
 
    Limpiar();
}//GEN-LAST:event_jButtonLimpiarActionPerformed

private void jFormattedTextFieldFechaInicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextFieldFechaInicioActionPerformed
 
}//GEN-LAST:event_jFormattedTextFieldFechaInicioActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InicioFiscalAgregarFrame().setVisible(true);
            }
        });
    }

    

   

    private void Limpiar() {
        this.jTextFieldIdInicioFiscal.setText("");
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        jFormattedTextFieldFechaInicio.setValue(mydate);
    }
    
    private void CrearNuevo(){
          try {
        Limpiar();


        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String sqlquery = "select count(*) as total from iniciofiscal where idmunicipio = ? ";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, sesion.getIdmunicipio());

        ResultSet rs = psquery.executeQuery();
        rs.next();
        int total = 0;
        int x = rs.getRow();
        if (x == 0) {
            total = 0;
        } else {
            total = Integer.parseInt(rs.getString("total"));
        }

        total++;
        jTextFieldIdInicioFiscal.setText(String.valueOf(total));


        repaint();

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    }
   
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JFormattedTextField jFormattedTextFieldFechaInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanelFondo;
    private javax.swing.JTextField jTextFieldIdInicioFiscal;
    // End of variables declaration//GEN-END:variables
}
